package fpig.io.structures

import fpig.lists.structures.FunList;
import fpig.util.CallUtil;
import groovy.lang.Closure;

import java.io.IOException
import java.io.InputStream;
import java.util.List;

class FunListInputStream extends InputStream {
    
	Closure untokenizer
    FunList currentList
    InputStream currentInput
	
	FunListInputStream(Closure _untokenizer, FunList _list){
		currentList = _list
		untokenizer = _untokenizer
	}

    //UGLY imperative code alert
    //TODO change this to recursive trampoline with less state mutation
	@Override
    int read() {
        int res = -1
        Closure nextInput = { ->
            if(currentList.empty){
                return null
            } else {
                def head = currentList.head
                currentList = currentList.tail
                currentInput = untokenizer(head)
            }
        }
        if(!currentInput){
            currentInput = nextInput()
            if(!currentInput){
                return -1
            }
        }
        res = currentInput.read()
        while(res ==-1){
            currentInput = nextInput()
            if(currentInput ==null){
                return -1
            }
            res = currentInput.read()
        }
        return res
    }

}
